package com.zat.mes.andrmes.dofun.work

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.media.RingtoneManager
import android.text.Editable
import android.text.InputType.TYPE_CLASS_NUMBER
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.base.BaseActivity
import com.zat.mes.andrmes.customerview.BottomSignDailog
import com.zat.mes.andrmes.customerview.HeadDateView
import com.zat.mes.andrmes.data.LoginResultBean
import com.zat.mes.andrmes.data.ParantTypeItem
import com.zat.mes.andrmes.dofun.QrScanActivity
import com.zat.mes.andrmes.dofun.qualitytest.vm.QcPlanViewModel
import com.zat.mes.andrmes.dofun.work.adapter.MotorWorkRecordAdapter
import com.zat.mes.andrmes.dofun.work.vm.HouseModel
import com.zat.mes.andrmes.dofun.work.vm.MotorWorkRecordModel
import com.zat.mes.andrmes.global.CompanionCode
import com.zat.mes.andrmes.global.CompanionType
import com.zat.mes.andrmes.utils.*
import kotlinx.android.synthetic.main.activity_in_house.*
import kotlinx.android.synthetic.main.activity_in_house.btnScanInhouse
import kotlinx.android.synthetic.main.activity_motor_work_record.*
import kotlinx.android.synthetic.main.activity_yarn_in.*
import kotlinx.android.synthetic.main.fragment_day_produce_plan.*
import kotlinx.android.synthetic.main.layout_head_clock.*
import kotlinx.android.synthetic.main.layout_title.*
import permissions.dispatcher.*
import java.util.*

/**
 * 电机
 */
@RuntimePermissions
class MotorWorkRecordActivity : BaseActivity() {

    var selectedDate = DateUtil.formatDate(Date(), DateUtil.FORMAT_3)
    var empId: Long = 0
    var qrCode:String?=""
    //U口读卡器,类似于外接键盘
    private var readCardUtils: ReadCardUtils? = null
    //仓库类型
    var house: MutableList<ParantTypeItem>? = null
    var qcModel: QcPlanViewModel? = null
    var houseModel: HouseModel? = null
    var motorWorkRecordModel: MotorWorkRecordModel? = null

    private var motorWorkRecordAdapter: MotorWorkRecordAdapter? = null

    override fun init() {
        initView()
        initData()
    }

    private fun initView() {
        setContentView(R.layout.activity_motor_work_record)
        tVtitle.text = "电机做工记录"
        rlReturnTitle.visibility = View.VISIBLE

        rlReturnTitle.setOnClickListener { finish() }

        btnScanInhouse.setOnClickListener {
            showCameraWithPermissionCheck()
        }
        setNumberBtn.setOnClickListener {
            if (motorWorkRecordAdapter!!.selectedIndex==-1){
                 showToast("请选择一条数据")
            }else{
                val inputEditTextField = EditText(this)
                inputEditTextField.inputType=TYPE_CLASS_NUMBER
                val dialog = AlertDialog.Builder(this)
                    .setTitle("")
                    .setMessage("请输入数量")
                    .setView(inputEditTextField)
                    .setPositiveButton("确定") { _, _ ->
                        val editTextInput = inputEditTextField .text.toString()
                        if (editTextInput.isEmpty()) {
                            showToast("请输入数量")
                            return@setPositiveButton
                        }
                        updateCount(editTextInput);

                    }
                    .setNegativeButton("取消", null)
                    .create()
                dialog.show()
            }
        }


    }

    fun  updateCount(editTextInput:String){
        motorWorkRecordModel?.updateProducedQty(editTextInput, motorWorkRecordAdapter!!.data[motorWorkRecordAdapter!!.selectedIndex].id.toString());

    }



    private fun initData() {
//读卡器声明
        readCardUtils = ReadCardUtils()
        initCardReader()

//        qcModel = ViewModelProvider(this).get(QcPlanViewModel::class.java)
//        qcModel?.getParantTypeData()?.observe(this, Observer {
//            closeLoading()
//            house = it.get("WAREHOUSE_STORAGE")
//        })
//        qcModel?.loadParantTypeList("WAREHOUSE_STORAGE")

        houseModel = ViewModelProvider(this).get(HouseModel::class.java)
        houseModel?.getPackData()?.observe(this, Observer {
            closeLoading()
//            machineId=it.packId.toString()
//            motorWorkRecordModel?.findProgramByMachineIddDate(selectedDate, machineId)
        })


        val loginResultBean = Gson().fromJson(
            PreferencesUtil.getString(CompanionType.LOGIN_RESULT),
            LoginResultBean::class.java
        )
        empId = loginResultBean.empid
        headDateView.setUserName(loginResultBean.empname)
        headDateView.setTimeName("选择日期")
        GlideUtil.setHeader(this, loginResultBean?.img, ivHeadClock)
        val timeListener = object : HeadDateView.OnHeadTimeSelectListener {
            override fun onTimeSelect(date: String) {
                selectedDate = date
                //进行接口的刷新 发送事件
               /// EventBus.getDefault().postSticky(WorkDayPlanEventMessage(selectedDate))
                motorWorkRecordModel?.findProgramByMachineIddDate(selectedDate, qrCode!!)

            }

        }
        headDateView.headTimeSelectListener = timeListener


        dataRV.layoutManager = LinearLayoutManager(this)
        motorWorkRecordAdapter =
            MotorWorkRecordAdapter(R.layout.item_motor_work_record)
        dataRV.adapter = motorWorkRecordAdapter
        motorWorkRecordAdapter!!.setOnItemClickListener { adapter, view, position ->
             motorWorkRecordAdapter!!.selectedIndex=position;
            motorWorkRecordAdapter!!.notifyDataSetChanged()
        }

        motorWorkRecordModel = ViewModelProvider(this).get(MotorWorkRecordModel::class.java)
        motorWorkRecordModel?.getMotorWorkRecordData()?.observe(this, Observer {
            closeLoading()
            if (it != null && it.size > 0) {
                setEmptyGone()
                setNumberBtn.visibility=View.VISIBLE
            } else {
                setEmptyVisible()
                setNumberBtn.visibility=View.GONE

            }
            motorWorkRecordAdapter!!.selectedIndex=-1
            motorWorkRecordAdapter?.setNewData(it)
        })
        if (qrCode!!.isNotEmpty()) {
            motorWorkRecordModel?.findProgramByMachineIddDate(selectedDate, qrCode!!)
            showLoading()
        }
        setEmptyVisible()



        motorWorkRecordModel?.getUpdateData()?.observe(this, Observer {
            closeLoading()
             if (it.isNullOrEmpty()){
                 motorWorkRecordModel?.findProgramByMachineIddDate(selectedDate, qrCode!!)
             }else
            showToast(it)
        })


    }

    /**
     * 初始化刷卡器
     */
    private fun initCardReader() {

        readCardUtils?.setReadSuccessListener(ReadCardUtils.OnReadSuccessListener() {
            Log.e("zhangyucode", "barcode: " + it);
            if (it.length == 8 || it.length == 10) {
                //叫唤
                val notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
                val r = RingtoneManager.getRingtone(applicationContext, notification)
                r.play()
//                val soundPool = SoundPool(2, AudioManager.STREAM_MUSIC, 0)
//                soundPool.load(this,R.raw.ondo,1)
//                soundPool.play(1,1f, 1f, 0, 0, 1f);
                showLoading()
                houseModel?.loadPackDataByRFRD(it)
            }
        })

    }

    /**
     * 设备刷卡监听
     */
    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        if (ReadCardUtils.isInputFromReader(this, event)) {
            if (readCardUtils != null) {
                readCardUtils?.resolveKeyEvent(event);
            }
        }
        return super.dispatchKeyEvent(event);

    }

    override fun onDestroy() {
        readCardUtils?.removeScanSuccessListener();
        readCardUtils = null;
        super.onDestroy()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        var qrCodes = data?.getStringExtra(CompanionType.INTENT_EXTRA_QRCODE)
        if (resultCode == Activity.RESULT_OK) {
            //根据二维码查包
            showLoading()
            qrCode=qrCodes
            motorWorkRecordModel?.findProgramByMachineIddDate(selectedDate, qrCode.toString())

           // houseModel?.loadPackData(qrCode)
        }
    }


    /**
     * 显示底部弹框 处理方式
     */
    fun showBottomDialog(list: MutableList<ParantTypeItem>?) {
        BottomSignDailog(this, list, object : BottomSignDailog.OnBottomSelectListener {
            override fun onBottomSelect(parantTypeItem: ParantTypeItem) {
                tvHouseInhouse.text = parantTypeItem.typename
                tvHouseInhouse.setTag(tvHouseInhouse.id, parantTypeItem)

            }

        })
    }

    @NeedsPermission(Manifest.permission.CAMERA)
    fun showCamera() {
        try {
            startActivityForResult(
                Intent(this, QrScanActivity::class.java),
                CompanionCode.REQUESTCODE
            )
        } catch (e: Exception) {
            Log.e("activity", e.toString())
        }
    }

    @OnShowRationale(Manifest.permission.CAMERA)
    fun showRationaleForCamera(request: PermissionRequest) {
        request.proceed();
        Log.e("permission", "OnShowRationale")
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    fun onCameraDenied() {
        showCameraWithPermissionCheck()
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    fun onCameraNeverAskAgain() {
//        showToast("请到设置打开相机权限")
        SystemActivityUtil.getAppDetailSettingIntent(this)
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        onRequestPermissionsResult(requestCode, grantResults)

    }
}
